package com.feihong.yw189.paidan.adapter;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.feihong.yw189.R;
import com.feihong.yw189.app.App;
import com.feihong.yw189.bluetooth.dialog.MyUsualyDialog;
import com.feihong.yw189.bluetooth.utils.util.ToastUtils;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.paidan.bean.ListOrderInfo;
import com.feihong.yw189.paidan.bean.PaiDanOrder;
import com.feihong.yw189.paidan.dialog.PaiDanShuoMingDialog;
import com.feihong.yw189.paidan.dialog.TuiDanDialog;
import com.feihong.yw189.paidan.inter.RefOrderListListener;
import com.feihong.yw189.paidan.inter.TuiDanListListener;
import com.feihong.yw189.paidan.qiangdanservice.LocationSDKTools;
import com.feihong.yw189.paidan.qiangdanservice.LocationUtils;
import com.google.gson.Gson;
import com.holenzhou.pullrecyclerview.BaseRecyclerAdapter;
import com.holenzhou.pullrecyclerview.BaseViewHolder;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.List;

import me.shaohui.bottomdialog.BottomDialog;

/**
 * 2018/1/24
 * 本数据适配器利用了 orderItemBean.getCity();来刷新item,如果项目中用到了这个值就得换其他值
 * 如果已完成就把状态跟在地址后面,并显示同步和取消按钮
 * 如果是其他状态就直接现在是在原来的位置
 */

public class NewListAdapter extends BaseRecyclerAdapter<ListOrderInfo.DataBean.OrderItemBean> {

    private Context mContext;
    private Activity mActivity;
    private BottomDialog locationDialog;

    private MyUsualyDialog dialog;
    private PopupWindow popupWindow;
    private String mCopiedText;
    private RefOrderListListener mRefOrderListListener;
    private ListOrderInfo.DataBean.OrderItemBean curentItem = null; // 当前item
    /**
     * @param context
     */
    public NewListAdapter(Context context, RefOrderListListener mRefOrderListListener) {
        super(context,R.layout.new_item_dispatch,new ArrayList<>());
        this.mContext = context;
        this.mActivity = (Activity) context;
        this.mRefOrderListListener = mRefOrderListListener;
        initPopupWindow();
        dialog = new MyUsualyDialog(mActivity, R.layout.chuli_item);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(false);
        locationDialog = BottomDialog.create(((AppCompatActivity) mContext).getSupportFragmentManager())//注意Adapter属于的Activity必须继承AppCompatActivity
                .setViewListener(new BottomDialog.ViewListener() {      // 可以进行一些必要对View的操作
                    @Override
                    public void bindView(View mapSheetView) {
                        // you can do bind view operation
                        mapSheetView.findViewById(R.id.baidu_btn).setOnClickListener(new NewListAdapter.locationButtonListener());
                        mapSheetView.findViewById(R.id.gaode_btn).setOnClickListener(new NewListAdapter.locationButtonListener());
                        mapSheetView.findViewById(R.id.tencent_btn).setOnClickListener(new NewListAdapter.locationButtonListener());
                        mapSheetView.findViewById(R.id.cancel_btn2).setOnClickListener(new NewListAdapter.locationButtonListener());
                    }
                })
                .setLayoutRes(R.layout.map_navagation_sheet)
                .setDimAmount(0.1f)            // Dialog window 背景色深度 范围：0 到 1，默认是0.2f
                .setCancelOutside(false)     // 点击外部区域是否关闭，默认true
                .setTag("DiTu");    // 设置DialogFragment的tag
        // .show();
    }

    public void setData(List<ListOrderInfo.DataBean.OrderItemBean> list) {
        notifyDataSetChanged();
    }

    @Override
    protected void convert(BaseViewHolder holder, ListOrderInfo.DataBean.OrderItemBean item) {

        setCopyWay(holder.getView(R.id.tv_order));
        setCopyWay(holder.getView(R.id.tv_name));
        setCopyWay(holder.getView(R.id.tv_address));


        holder.setText(R.id.tv_order,item.getOrder_sn());
        holder.setText(R.id.tv_name,item.getUser_name());
        holder.setText(R.id.tv_address,item.getAddress());
        holder.setText(R.id.order_area_tv,item.getCity() + item.getArea());
        holder.setText(R.id.tv_time,item.getLast_time());
        holder.setText(R.id.tv_endtime,item.getGoods_name());

        holder.setOnClickListener(R.id.tv_endtime,v -> {
            String note1 = item.getNote();// 获取订单说明
            String gdName = item.getGoods_name();// 获取订单说明

            PaiDanShuoMingDialog paiDanShuoMingDialog = new PaiDanShuoMingDialog(mActivity);
            paiDanShuoMingDialog.setContent(gdName, note1);
            paiDanShuoMingDialog.setCanceledOnTouchOutside(false);
            paiDanShuoMingDialog.setCancelable(false);
            paiDanShuoMingDialog.show();
        });

        holder.setOnClickListener(R.id.pd_cancle,v -> {
            TuiDanDialog tuiDanDialog = new TuiDanDialog(mContext, "提示", "请确认是否接该订单？", new TuiDanListListener() {
                @Override
                public void onCancleOrder(String str, int type) {
                    String orderSn = item.getOrder_sn();
                    // 接单
                    jieDan(orderSn);
                }
            });
            tuiDanDialog.setCanceledOnTouchOutside(false);
            tuiDanDialog.setCancelable(false);
            tuiDanDialog.show();
        });

        holder.getView(R.id.tv_map).setTag(item);
        holder.setOnClickListener(R.id.tv_map,view -> {

            if (!locationDialog.isVisible()) {
                curentItem = (ListOrderInfo.DataBean.OrderItemBean) view.getTag();
                locationDialog.show();
            }
        });
    }

    private void initPopupWindow() {
        View popupView = mActivity.getLayoutInflater().inflate(R.layout.tpl_select_menu, null);

        popupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable(mActivity.getResources(), (Bitmap) null));

        TextView select_menu_copy = (TextView) popupView.findViewById(R.id.select_menu_copy);

        select_menu_copy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ClipboardManager cm = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clip = ClipData.newPlainText(null, mCopiedText);
                cm.setPrimaryClip(clip);
                ToastUtils.showShortToast(mActivity, "内容已复制到剪切板,快去粘贴吧!");
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
            }
        });
    }

    private void setCopyWay(final TextView tv) {
        tv.setOnLongClickListener(v -> {
                    mCopiedText = ((TextView) v).getText().toString();
                    popupWindow.showAsDropDown(v);
                return false;
        });
    }


    private void jieDan(String orderSn) {
        dialog.show();
        // 接单
        App.getApp().getHttpTools().jieDanRequest(orderSn, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                try {
                    Gson gson = new Gson();
                    PaiDanOrder paiDanOrder = gson.fromJson(result, PaiDanOrder.class);
                    if (paiDanOrder != null) {
                        int status = paiDanOrder.getStatus();
                        if (status == 1) {
                            // 刷新列表
                            mRefOrderListListener.onRefreshOrder();
                        }
                        ToastUtils.showShortToast(mActivity, paiDanOrder.getInfo());
                    } else {
                        ToastUtils.showShortToast(mActivity, "服务器返回数据为空");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtils.showShortToast(mActivity, "接单失败请重试");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                ToastUtils.showShortToast(mActivity, "网络错误");
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    private class locationButtonListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {

            try {

                LocationUtils locationUtils = new LocationUtils();
                locationUtils.setLatitude(Double.parseDouble(curentItem.getLast_gps_latitude().toString()));
                locationUtils.setLongitude(Double.parseDouble(curentItem.getLast_gps_longitude().toString()));
                if (!TextUtils.isEmpty(curentItem.getLt_address())) {

                    locationUtils.setName(curentItem.getLt_address());

                } else {
                    locationUtils.setName("");
                }
                LocationSDKTools sdkTools = new LocationSDKTools(mContext);

                switch (v.getId()) {
                    case R.id.baidu_btn:
                        sdkTools.GOTO(LocationSDKTools.TYPE_BAIDU, locationUtils);
                        break;
                    case R.id.gaode_btn:
                        sdkTools.GOTO(LocationSDKTools.TYPE_GAODE, locationUtils);
                        break;
                    case R.id.tencent_btn:
                        sdkTools.GOTO(LocationSDKTools.TYPE_TENGXUN, locationUtils);
                        break;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                Toast.makeText(mContext, "无法启动地图", Toast.LENGTH_SHORT).show();
            }
            locationDialog.dismiss();

        }
    }

}
